package org.jeecg.modules.paycenter.channel.zzbank.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.*;
import cn.hutool.json.JSONUtil;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.constant.PayConstants;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.annotation.RequestLog;
import org.jeecg.modules.paycenter.channel.constant.CommonConstants;
import org.jeecg.modules.paycenter.channel.zzbank.dto.CorSinglePayDto;
import org.jeecg.modules.paycenter.channel.zzbank.dto.CreateSubAccountDto;
import org.jeecg.modules.paycenter.channel.zzbank.entity.HyZzbankAccount;
import org.jeecg.modules.paycenter.channel.zzbank.service.IHyZzbankAccountService;
import org.jeecg.modules.paycenter.channel.zzbank.util.SnowFlakeUtil;
import org.jeecg.modules.paycenter.channel.zzbank.vo.WithdrawalVo;
import org.jeecg.modules.paycenter.enums.UTypeEnum;
import org.jeecg.modules.paycenter.service.ZhengZhouPayService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.third.sendsms.service.SendSmsService;
import org.jeecg.modules.wlhy.bill.entity.HyCaptainBill;
import org.jeecg.modules.wlhy.bill.entity.HyDriverBill;
import org.jeecg.modules.wlhy.bill.service.IHyCaptainBillService;
import org.jeecg.modules.wlhy.bill.service.IHyDriverBillService;
import org.jeecg.modules.wlhy.captain.entity.HyCaptain;
import org.jeecg.modules.wlhy.captain.service.IHyCaptainService;
import org.jeecg.modules.wlhy.company.entity.HyCompany;
import org.jeecg.modules.wlhy.company.service.IHyCompanyService;
import org.jeecg.modules.wlhy.customer.entity.HyCustomer;
import org.jeecg.modules.wlhy.customer.service.IHyCustomerService;
import org.jeecg.modules.wlhy.hybank.service.IHyBankService;
import org.jeecg.modules.wlhy.hycarrier.entity.HyCarrier;
import org.jeecg.modules.wlhy.hycarrier.service.IHyCarrierService;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriver;
import org.jeecg.modules.wlhy.hydriver.service.IHyDriverService;
import org.jeecg.modules.wlhy.hydriverbank.entity.HyDriverBank;
import org.jeecg.modules.wlhy.setting.entity.HySetting;
import org.jeecg.modules.wlhy.setting.service.IHySettingService;
import org.jeecg.modules.wlhy.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Description: hy_bank
 * @Author: jeecg-boot
 * @Date:   2021-11-26
 * @Version: V1.0
 */
@Api(tags="hy_bank")
@RestController
@RequestMapping("/hyzzbank")
@Slf4j
public class HyZhengZhouBankController extends JeecgController<HyZzbankAccount, IHyZzbankAccountService> {

    @Value("${pingan.cashout.active}")
    private String CASHOUT_ACTIVE;

    @Value("${pingan.cashout.begin}")
    private String CASHOUT_BEGIN;

    @Value("${pingan.cashout.end}")
    private String CASHOUT_END;

    @Value("${pingan.cashout.sms-active}")
    private String CASH_OUT_SMS_ACTIVE;

    @Value("${pingan.acc-sms-active}")
    private String ACC_SMS_ACTIVE;

    @Resource
    private IHyZzbankAccountService accountService;
    @Resource
    IHyDriverService hyDriverService;

    @Resource
    IHyCarrierService carrierService;

    @Resource
    IHyCustomerService customerService;

    @Resource
    IHyCompanyService companyService;

    @Resource
    IHyCaptainService captainService;

    @Resource
    private ISysUserService userService;

    @Resource
    private IHyDriverBillService driverBillService;

    @Resource
    private IHyCaptainBillService hyCaptainBillService;

    @Resource
    private IHySettingService settingService;

    @Lazy
    @Resource
    private RedisUtil redisUtil;

    @Resource
    private SendSmsService sendSmsService;



    //创建郑州银行清分账户接口
    @RequestLog(description = "清分台账子账号开通")
    @PostMapping("/createSubAccount")
    public R createSubAccount(@RequestBody CreateSubAccountDto createSubAccountDto) {
        //如果Utype是1，则检查平台是否开通了清分账户
        if (UTypeEnum.SYSUSER.uType.equalsIgnoreCase(createSubAccountDto.getUtype())) {
            HyZzbankAccount plateSubAcc = accountService.lambdaQuery().eq(HyZzbankAccount::getUtype, UTypeEnum.SYSUSER.uType).one();
            if (ObjUtil.isNotEmpty(plateSubAcc)) {
                return R.failed("已经开通过了平台账号，请勿重复开通");
            }
        } else {
            //首先查询该用户是否已经开通了子账户

            HyZzbankAccount account = null;
            if (createSubAccountDto.getUtype().equalsIgnoreCase(UTypeEnum.CARRIER.uType)) {
                account = validateAccountInfo(createSubAccountDto.getCarrierId(), createSubAccountDto.getUtype());
            } else if(createSubAccountDto.getUtype().equalsIgnoreCase(UTypeEnum.COMPANY.uType)) {
                account = validateAccountInfo(createSubAccountDto.getCompanyId(), createSubAccountDto.getUtype());
            } else {
                account = validateAccountInfo(createSubAccountDto.getUid(), createSubAccountDto.getUtype());

            }

            if (ObjUtil.isNotEmpty(account)) {
                return R.failed("已经开通过了！");
            }
        }

        String result = "";
        //首先查询用户是否存在
        if(UTypeEnum.CARRIER.uType.equalsIgnoreCase(createSubAccountDto.getUtype())) { //车队长
            HyCarrier carrierInfo = carrierService.getById(createSubAccountDto.getCarrierId());
            if (ObjUtil.isEmpty(carrierInfo)) {
                return R.failed("车队长信息异常, 查不到车队长信息");
            }
            SysUser loginUser = userService.lambdaQuery().eq(SysUser::getId, createSubAccountDto.getUid()).one();
            if (ObjUtil.isNotEmpty(loginUser) && !loginUser.getUType().equalsIgnoreCase(UTypeEnum.SYSUSER.uType)) {
                //非系统用户需要验证货主信息
                HyCustomer customer = customerService.lambdaQuery().eq(HyCustomer::getUserId, createSubAccountDto.getUid()).one();
                if (ObjUtil.isEmpty(customer)) {
                    return R.failed("车队长信息异常, 查不到货主信息");
                }
            }
            //开始创建车队长信息
            createSubAccountDto.setUid(carrierInfo.getId());
            createSubAccountDto.setAccName(carrierInfo.getBankName());
            accountService.createSubAccount(createSubAccountDto);

        } else if (UTypeEnum.CUSTOMER.uType.equalsIgnoreCase(createSubAccountDto.getUtype())) {//货主
            HyCustomer customerInfo = customerService.lambdaQuery().eq(HyCustomer::getUserId, createSubAccountDto.getUid()).one();
            createSubAccountDto.setUid(customerInfo.getId());
            createSubAccountDto.setAccName(customerInfo.getCustomerName());
            accountService.createSubAccount(createSubAccountDto);
        } else if (UTypeEnum.DRIVER.uType.equalsIgnoreCase(createSubAccountDto.getUtype())) { // 司机
            HyDriver driverInfo = hyDriverService.lambdaQuery().eq(HyDriver::getUserId, createSubAccountDto.getUid()).one();
            if (ObjUtil.isEmpty(driverInfo)) {
                return R.failed("司机账户异常");
            }
            createSubAccountDto.setUid(driverInfo.getId());
            createSubAccountDto.setAccName(driverInfo.getDriverName());
            accountService.createSubAccount(createSubAccountDto);
        } else if (UTypeEnum.SYSUSER.uType.equalsIgnoreCase(createSubAccountDto.getUtype())) { //平台 utype=1
            createSubAccountDto.setUid("1");
            createSubAccountDto.setAccName(createSubAccountDto.getAccName());
            accountService.createSubAccount(createSubAccountDto);
        } else if (UTypeEnum.COMPANY.uType.equalsIgnoreCase(createSubAccountDto.getUtype())) { //分公司
            HyCompany companyInfo = companyService.getById(createSubAccountDto.getCompanyId());
            createSubAccountDto.setUid(companyInfo.getId());
            createSubAccountDto.setAccName(companyInfo.getCompanyName());
            accountService.createSubAccount(createSubAccountDto);
        } else if (UTypeEnum.CAPTAIN.uType.equalsIgnoreCase(createSubAccountDto.getUtype())){ //承运商
            HyCaptain captainInfo = captainService.lambdaQuery().eq(HyCaptain::getUserId, createSubAccountDto.getUid()).one();
            createSubAccountDto.setUid(captainInfo.getId());
            createSubAccountDto.setAccName(captainInfo.getCaptainName());
            accountService.createSubAccount(createSubAccountDto);
        }
        return R.ok("账户开通成功");
    }

    @RequestLog(description = "清分台账编码余额查询")
    @GetMapping("/subAccountInfo")
    public R subAccountBalanceQuery(@NotBlank(message = "uid不能为空")  @RequestParam("uid") String  uid,
                                    @NotBlank(message = "utype不能为空") @RequestParam("utype") String utype) {
        HyZzbankAccount account = validateAccountInfo(uid, utype);
        if (ObjUtil.isEmpty(account)) {
            return R.failed("没有查到账户信息");
        }
        account.setAmt(accountService.subAccountInfoByAccNo(account.getSubAccount()));
        return R.ok(account);

    }

    @RequestLog(description = "根据账户清分台账编码余额查询")
    @GetMapping("/subAccountInfoByAcc")
    public R subAccountBalanceQuery(@RequestParam("accNo") String accNo) {
        HyZzbankAccount account = accountService.lambdaQuery().eq(HyZzbankAccount::getSubAccount, accNo).one();
        if (ObjUtil.isEmpty(account)) {
            return   R.failed("没有查到账户信息");
        }
        account.setAmt(accountService.subAccountInfoByAccNo(account.getSubAccount()));
        return R.ok(account);

    }

    @RequestLog(description = "根据账户清分台账编码余额查询")
    @GetMapping("/subAccountInfoByAcc/test")
    public R subAccountBalanceTestQuery(@RequestParam("accNo") String accNo) {
        return R.ok(accountService.subAccountInfoByAccNo(accNo));

    }

    @RequestLog(description = "银行提现交易结果查询")
    @GetMapping("corSingleTransferQuery")
    public R corSingleTransferQuery(@RequestParam("billId") String billId,
                                    @RequestParam("utype") String utype) {
        if (UTypeEnum.DRIVER.uType.equalsIgnoreCase(utype)) { //司机
            HyDriverBill driverBill = driverBillService.getById(billId);
            if (ObjUtil.isEmpty(driverBill)) {
                return R.failed("没有查到司机提现流水单");
            }
            if (!"2".equals(driverBill.getBillType())) {
                return R.failed("司机提现流水单状态错误");
            }
            //根据流水号查询交易结果，交易结果回返回成交流水号
            String startDate = DateUtil.format(DateUtil.offsetDay(driverBill.getCreateTime(), -1), "yyyy-MM-dd");
            String endDate = DateUtil.format(DateUtil.offsetDay(driverBill.getCreateTime(), 1), "yyyy-MM-dd");
            log.info("开始查询交易数据---");
            Map<String, String> transResultMap = accountService.queryTransferResult(driverBill.getBillNum(), driverBill.getFrontFlowNo(),driverBill.getDbaccno(), "1", startDate, endDate);
            log.info("开始查询交易数据结果为---"+transResultMap.toString());
            if (ObjUtil.isNotEmpty(transResultMap)) {
                String transStatus = transResultMap.get("TransStatus");
                if ("0".equals(transStatus)) {//交易成功
                    driverBill.setRespSource(CommonConstants.SUCCESS.toString());
                    driverBill.setRespCode(PayConstants.BANK_PAY_SOUR.SUCCESS);
                    driverBill.setRespInfo("提现成功");
                } else if ("1".equals(transStatus)) {
                    driverBill.setRespSource(CommonConstants.FAIL.toString());
                    driverBill.setRespCode(PayConstants.BANK_PAY_SOUR.FAIL);
                    driverBill.setRespInfo("提现失败");
                } else if ("2".equals(transStatus)) {
                    driverBill.setRespSource(CommonConstants.FAIL.toString());
                    driverBill.setRespCode(PayConstants.BANK_PAY_SOUR.FAIL);
                    driverBill.setRespInfo("提现异常，状态未名");
                } else if ("3".equals(transStatus)) {
                    driverBill.setRespSource(CommonConstants.FAIL.toString());
                    driverBill.setRespCode(PayConstants.BANK_PAY_SOUR.FAIL);
                    driverBill.setRespInfo("提现状态-在途");
                }else if ("4".equals(transStatus)) {
                    driverBill.setRespSource(CommonConstants.FAIL.toString());
                    driverBill.setRespCode(PayConstants.BANK_PAY_SOUR.FAIL);
                    driverBill.setRespInfo("提现状态-不存在");
                }else if ("5".equals(transStatus)) {
                    driverBill.setRespSource(CommonConstants.FAIL.toString());
                    driverBill.setRespCode(PayConstants.BANK_PAY_SOUR.FAIL);
                    driverBill.setRespInfo("提现状态-转代付账户失败");
                }else if ("6".equals(transStatus)) {
                    driverBill.setRespSource(CommonConstants.FAIL.toString());
                    driverBill.setRespCode(PayConstants.BANK_PAY_SOUR.FAIL);
                    driverBill.setRespInfo("提现状态-转代付账户成功");
                }else if ("7".equals(transStatus)) {
                    driverBill.setRespSource(CommonConstants.FAIL.toString());
                    driverBill.setRespCode(PayConstants.BANK_PAY_SOUR.FAIL);
                    driverBill.setRespInfo("提现状态-转代付账户成功，转收款账户失败");
                }else if ("8".equals(transStatus)) {
                    driverBill.setRespSource(CommonConstants.FAIL.toString());
                    driverBill.setRespCode(PayConstants.BANK_PAY_SOUR.FAIL);
                    driverBill.setRespInfo("提现状态-转代付账户成功，转收款账户成功");
                }else if ("9".equals(transStatus)) {
                    driverBill.setRespSource(CommonConstants.FAIL.toString());
                    driverBill.setRespCode(PayConstants.BANK_PAY_SOUR.FAIL);
                    driverBill.setRespInfo("提现状态-转代付账户成功，转收款账户处理中");
                }else if ("10".equals(transStatus)) {
                    driverBill.setRespSource(CommonConstants.FAIL.toString());
                    driverBill.setRespCode(PayConstants.BANK_PAY_SOUR.FAIL);
                    driverBill.setRespInfo("提现状态-待银行审核");
                }
                driverBillService.updateById(driverBill);
            }
            return R.ok(driverBill);
        }

        return R.failed();

    }

    @RequestLog(description = "承运商银行提现交易结果查询")
    @GetMapping("corSingleTransferQuery4Captain")
    public R corSingleTransferQuery4Captain(@RequestParam("billId") String billId,
                                    @RequestParam("utype") String utype) {
        if (UTypeEnum.CAPTAIN.uType.equalsIgnoreCase(utype)) { //承运商
            HyCaptainBill hyCaptainBill = hyCaptainBillService.getById(billId);
            if (ObjUtil.isEmpty(hyCaptainBill)) {
                return R.failed("没有查到承运商提现流水单");
            }
            if (!"2".equals(hyCaptainBill.getBillType())) {
                return R.failed("承运商提现流水单状态错误");
            }
            //根据流水号查询交易结果，交易结果回返回成交流水号
            String startDate = DateUtil.format(DateUtil.offsetDay(hyCaptainBill.getCreateTime(), -1), "yyyy-MM-dd");
            String endDate = DateUtil.format(DateUtil.offsetDay(hyCaptainBill.getCreateTime(), 1), "yyyy-MM-dd");
            log.info("开始查询交易数据---");
            Map<String, String> transResultMap = accountService.queryTransferResult(hyCaptainBill.getBillNum(), hyCaptainBill.getFrontFlowNo(),hyCaptainBill.getDbaccno(), "1", startDate, endDate);
            log.info("开始查询交易数据结果为---"+transResultMap.toString());
            if (ObjUtil.isNotEmpty(transResultMap)) {
                String transStatus = transResultMap.get("TransStatus");
                if ("0".equals(transStatus)) {//交易成功
                    hyCaptainBill.setRespSource(CommonConstants.SUCCESS.toString());
                    hyCaptainBill.setRespCode(PayConstants.BANK_PAY_SOUR.SUCCESS);
                    hyCaptainBill.setRespInfo("提现成功");
                } else if ("1".equals(transStatus)) {
                    hyCaptainBill.setRespSource(CommonConstants.FAIL.toString());
                    hyCaptainBill.setRespCode(PayConstants.BANK_PAY_SOUR.FAIL);
                    hyCaptainBill.setRespInfo("提现失败");
                } else if ("2".equals(transStatus)) {
                    hyCaptainBill.setRespSource(CommonConstants.FAIL.toString());
                    hyCaptainBill.setRespCode(PayConstants.BANK_PAY_SOUR.FAIL);
                    hyCaptainBill.setRespInfo("提现异常，状态未名");
                } else if ("3".equals(transStatus)) {
                    hyCaptainBill.setRespSource(CommonConstants.FAIL.toString());
                    hyCaptainBill.setRespCode(PayConstants.BANK_PAY_SOUR.FAIL);
                    hyCaptainBill.setRespInfo("提现状态-在途");
                }else if ("4".equals(transStatus)) {
                    hyCaptainBill.setRespSource(CommonConstants.FAIL.toString());
                    hyCaptainBill.setRespCode(PayConstants.BANK_PAY_SOUR.FAIL);
                    hyCaptainBill.setRespInfo("提现状态-不存在");
                }else if ("5".equals(transStatus)) {
                    hyCaptainBill.setRespSource(CommonConstants.FAIL.toString());
                    hyCaptainBill.setRespCode(PayConstants.BANK_PAY_SOUR.FAIL);
                    hyCaptainBill.setRespInfo("提现状态-转代付账户失败");
                }else if ("6".equals(transStatus)) {
                    hyCaptainBill.setRespSource(CommonConstants.FAIL.toString());
                    hyCaptainBill.setRespCode(PayConstants.BANK_PAY_SOUR.FAIL);
                    hyCaptainBill.setRespInfo("提现状态-转代付账户成功");
                }else if ("7".equals(transStatus)) {
                    hyCaptainBill.setRespSource(CommonConstants.FAIL.toString());
                    hyCaptainBill.setRespCode(PayConstants.BANK_PAY_SOUR.FAIL);
                    hyCaptainBill.setRespInfo("提现状态-转代付账户成功，转收款账户失败");
                }else if ("8".equals(transStatus)) {
                    hyCaptainBill.setRespSource(CommonConstants.FAIL.toString());
                    hyCaptainBill.setRespCode(PayConstants.BANK_PAY_SOUR.FAIL);
                    hyCaptainBill.setRespInfo("提现状态-转代付账户成功，转收款账户成功");
                }else if ("9".equals(transStatus)) {
                    hyCaptainBill.setRespSource(CommonConstants.FAIL.toString());
                    hyCaptainBill.setRespCode(PayConstants.BANK_PAY_SOUR.FAIL);
                    hyCaptainBill.setRespInfo("提现状态-转代付账户成功，转收款账户处理中");
                }else if ("10".equals(transStatus)) {
                    hyCaptainBill.setRespSource(CommonConstants.FAIL.toString());
                    hyCaptainBill.setRespCode(PayConstants.BANK_PAY_SOUR.FAIL);
                    hyCaptainBill.setRespInfo("提现状态-待银行审核");
                }
                hyCaptainBillService.updateById(hyCaptainBill);
            }
            return R.ok(hyCaptainBill);
        }

        return R.failed();

    }
    HyZzbankAccount validateAccountInfo(String uid, String utype) {
        HyZzbankAccount account = new HyZzbankAccount();
        if (UTypeEnum.DRIVER.uType.equalsIgnoreCase(utype)) { //司机
            HyDriver driverInfo = hyDriverService.lambdaQuery().eq(HyDriver::getUserId, uid).one();
            account = accountService.lambdaQuery()
                    .eq(HyZzbankAccount::getUid, driverInfo.getId())
                    .eq(HyZzbankAccount::getUtype, UTypeEnum.DRIVER.uType)
                    .one();
        } else if (UTypeEnum.CUSTOMER.uType.equalsIgnoreCase(utype)) {//货主
            HyCustomer customerInfo = customerService.lambdaQuery().eq(HyCustomer::getUserId, uid).one();
            account = accountService.lambdaQuery()
                    .eq(HyZzbankAccount::getUid, customerInfo.getId())
                    .eq(HyZzbankAccount::getUtype, UTypeEnum.CUSTOMER.uType)
                    .one();
        } else if (UTypeEnum.CARRIER.uType.equalsIgnoreCase(utype)) {//车队长
            account = accountService.lambdaQuery()
                    .eq(HyZzbankAccount::getUid, uid)
                    .eq(HyZzbankAccount::getUtype, UTypeEnum.CARRIER.uType)
                    .one();
        } else if (UTypeEnum.CAPTAIN.uType.equalsIgnoreCase(utype)) {//承运商
            account = accountService.lambdaQuery()
                    .eq(HyZzbankAccount::getUid, uid)
                    .eq(HyZzbankAccount::getUtype, UTypeEnum.CAPTAIN.uType)
                    .one();
        } else {//其他
            account = accountService.lambdaQuery().eq(HyZzbankAccount::getUid, uid).one();
        }
        return account;
    }



    @RequestLog(description = "根据流水号下载司机的银行回单")
    @PostMapping("/downloadReceipt")
    public R downloadReceipt(@RequestParam("billNum") String billNum) throws Exception {
        HyDriverBill driverBill = driverBillService.lambdaQuery().eq(HyDriverBill::getBillNum, billNum).one();
        if (ObjUtil.isEmpty(driverBill)) {
            return R.failed("没有查到流水单信息");
        }
        return accountService.downloadReceipt4Driver(driverBill);

    }


    @RequestLog(description = "根据流水号下载司机的银行回单")
    @PostMapping("/downloadReceiptTest")
    public R downloadReceiptTest(@RequestParam("fileName") String fileName) throws Exception {
        return R.ok(accountService.downloadReceipt4DriverByFileName(fileName));

    }

    @RequestLog(description = "子账号到外部账号--提现")
    @PostMapping("cashOut")
    public R cashOut(@RequestBody CorSinglePayDto singlePayDto) throws Exception {
        if ("1".equalsIgnoreCase(CASHOUT_ACTIVE)
                &&( DateUtil.hour(new Date(), true)>Integer.parseInt(CASHOUT_END) || DateUtil.hour(new Date(), true) <Integer.parseInt(CASHOUT_BEGIN))){
            return R.failed("不在交易时间内, 详情请咨询系统管理员！");
        }

        if ("1".equalsIgnoreCase(CASH_OUT_SMS_ACTIVE)) {
            String mobilePhone = "";
            if(Objects.equals(singlePayDto.getOutUtype(), UTypeEnum.DRIVER.uType)) {
                HyDriver driverInfo = hyDriverService.lambdaQuery()
                        .eq(HyDriver::getUserId, singlePayDto.getOutUid()).one();
                if (ObjUtil.isEmpty(driverInfo)) {
                    return R.failed("没有查到有效的司机信息");
                }
                mobilePhone = driverInfo.getTelephone();
            }
            if (UTypeEnum.CARRIER.uType.equalsIgnoreCase(singlePayDto.getOutUtype())) {
                HyCarrier carrierInfo = carrierService.getById(singlePayDto.getOutUid());
                if (ObjUtil.isEmpty(carrierInfo)) {
                    return R.failed("没有查到有效的信息");
                }
                mobilePhone = carrierInfo.getTel();

            }
            Object code = redisUtil.get(mobilePhone);
            if (ObjUtil.isEmpty(singlePayDto.getMobileCode()) || !singlePayDto.getMobileCode().equals(code)) {
                return R.failed("验证码错误！");
            }
        }

        HyZzbankAccount outAccountInfo = validateAccountInfo(singlePayDto.getOutUid(), singlePayDto.getOutUtype());

        if (ObjUtil.isEmpty(outAccountInfo)) {
            return R.failed("转出账号为空");
        }

        //校验是否是本人银行卡
        if("1".equals(settingService.lambdaQuery()
                .like(HySetting::getTag, "self_bankcard")
                .one().getData())) {
            String accName = "";
            if (UTypeEnum.DRIVER.uType.equalsIgnoreCase(singlePayDto.getOutUtype())) {
                HyDriver hyDriver = hyDriverService.lambdaQuery().eq(HyDriver::getUserId, singlePayDto.getOutUid()).one();
                accName = hyDriver.getDriverName();
            } else if (UTypeEnum.CARRIER.uType.equalsIgnoreCase(singlePayDto.getOutUtype())) {
                HyCarrier carrierInfo = carrierService.getById(singlePayDto.getOutUid());
                accName = carrierInfo.getCarrierName();
            }
            if (!accName.equalsIgnoreCase(singlePayDto.getInAcctName())) {
                log.info("不是本人银行卡,禁止提现");
                return R.failed("当前系统已限定绑定本人银行卡，请联系平台管理员");
            }
        }

        String accAmt = accountService.subAccountInfoByAccNo(outAccountInfo.getSubAccount());
        //如果报错
        if (StrUtil.isBlank(accAmt)) {
            return R.failed("没有查到子账户信息");
        }

        BigDecimal available = new BigDecimal(accAmt);

        if (!NumberUtil.isGreaterOrEqual(available, new BigDecimal(singlePayDto.getTranAmount()))) {
            return R.failed("账户余额不足");
        } else {
            singlePayDto.setUseEx("司机提现");
            return R.ok(accountService.transfer4All(singlePayDto, outAccountInfo));
        }
    }


    @RequestLog(description = "提现短信")
    @PostMapping("/sms/cashOut")
    public R cashOutSMS(@RequestParam("uid") String uid,
                        @RequestParam("utype") String utype) throws Exception {
        if ("1".equalsIgnoreCase(CASHOUT_ACTIVE)
                &&( DateUtil.hour(new Date(), true)>Integer.parseInt(CASHOUT_END) || DateUtil.hour(new Date(), true) <Integer.parseInt(CASHOUT_BEGIN))){
            return R.failed("不在交易时间内, 详情请咨询系统管理员！");
        }


        String mobilePhone = "";
        if(Objects.equals(utype, UTypeEnum.DRIVER.uType)) {
            HyDriver driverInfo = hyDriverService.lambdaQuery().eq(HyDriver::getUserId, uid).one();
            if (ObjUtil.isEmpty(driverInfo)) {
                return R.failed("没有查到有效的司机信息");
            }
            mobilePhone = driverInfo.getTelephone();
        }
        if (UTypeEnum.CARRIER.uType.equalsIgnoreCase(utype)) {
            HyCarrier carrierInfo = carrierService.getById(uid);
            mobilePhone = carrierInfo.getTel();

        }

        if (UTypeEnum.CAPTAIN.uType.equalsIgnoreCase(utype)) {
            HyCaptain captainInfo = captainService.getById(uid);
            mobilePhone = captainInfo.getLoginPhone();

        }
        log.info("提现发送手机号验证开始");
        if (StrUtil.isEmpty(mobilePhone) || mobilePhone.length() != 11) {
            return R.failed("手机号长度错误");
        }
        if (!mobilePhone.matches(CommonConstants.REGEX_MOBILE)) {
            return R.failed("手机号格式错误");
        }
        long expire = redisUtil.getExpire(mobilePhone);
        //有效期没超过2分钟  (5-2)*60
        if (expire > 60*2) {
            return R.failed("获取验证码间隔为2分钟，请稍后重试！");
        }

        //随机数
        String captcha = RandomUtil.randomNumbers(6);
        Map<String, String> obj = new HashMap<>();
        obj.put("code", captcha);
        obj.put("number", "2");
        if (!sendSmsService.sendSms(mobilePhone, obj)) {
            return R.failed("短信验证码发送失败,请稍后重试");
        }
        redisUtil.set(mobilePhone, captcha, 60*2);
        log.info("提现发送手机号验证结束，手机号：{}, 验证码：{}", mobilePhone, captcha);
        return R.ok(PhoneUtil.hideBetween(mobilePhone), "发送成功");
    }
    @RequestLog(description = "是否开启短信验证")
    @PostMapping("/sms/smsVerificationFlag")
    public R smsVerificationFlag() throws Exception {
        Map<String, String> result = new HashMap<>();
        result.put("acc_sms_active", ACC_SMS_ACTIVE);
        result.put("cashout_sms_active", CASH_OUT_SMS_ACTIVE);
        return R.ok(result,"请求成功！");
    }

    @RequestLog(description = "根据customerId查询货主的账户余额")
    @GetMapping("/subAccountInfo/byCustomerId")
    public R customerBalanceByCustomerId(@RequestParam("customerId") String  customerId) {
        if (ObjUtil.isEmpty(customerId)) {
            return R.failed("customerId不能为空");
        }
        HyZzbankAccount account = accountService.lambdaQuery().eq(HyZzbankAccount::getUid, customerId).one();
        if (ObjUtil.isEmpty(account)) {
            return  R.failed("没有查到账户信息");
        }
        account.setAmt(accountService.subAccountInfoByAccNo(account.getSubAccount()));
        return R.ok(account);
    }
}
